package sessionBeans;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entities.FormaPago;
import entities.FormaVenta;
import exceptions.EntityAlreadyExistException;

/**
 * Session Bean implementation class AdministradorCodificadoresBean
 */
@Stateless
public class AdministradorCodificadoresBean implements AdministradorCodificadores {

    @PersistenceContext(unitName="CRM")
    private EntityManager em;
    
    public AdministradorCodificadoresBean() {
        // TODO Auto-generated constructor stub
    }
	@SuppressWarnings("unchecked")
	@Override
	public FormaPago buscarFormaPago(String nombre){
		Query q = em.createQuery("from FormaPago a where lower(a.forma) like :nom");
		q.setParameter("nom", nombre.toLowerCase());
		FormaPago form = null;
		List<FormaPago> formas = (ArrayList<FormaPago>) q.getResultList();
		if(!formas.isEmpty()){
			form = formas.get(0);
		}
		return form;
	}

	@Override
	public boolean grabarFormaPago(FormaPago forma) throws EntityAlreadyExistException {
		FormaPago form1 = this.buscarFormaPago(forma.getForma());
		if(form1!=null){
			throw new EntityAlreadyExistException("FormaPago: "+forma.getForma());
		}
		try{
			this.em.persist(forma);
			return true;
		} catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public FormaVenta buscarFormaVenta(String nombre) {
		Query q = em.createQuery("from FormaVenta a where lower(a.forma) like :nom");
		q.setParameter("nom", nombre.toLowerCase());
		FormaVenta form = null;
		List<FormaVenta> formas = (ArrayList<FormaVenta>) q.getResultList();
		if(!formas.isEmpty()){
			form = formas.get(0);
		}
		return form;
	}

	@Override
	public boolean grabarFormaVenta(FormaVenta forma)
			throws EntityAlreadyExistException {
		FormaVenta form1 = this.buscarFormaVenta(forma.getForma());
		if(form1!=null){
			throw new EntityAlreadyExistException("FormaVenta: "+forma.getForma());
		}
		try{
			this.em.persist(forma);
			return true;
		} catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}



}
